package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.stark.imgedit.model.ColorTuneRange;
import com.stark.imgedit.utils.BmpUtil;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityPicAdjustBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.RxUtil;

public class PicAdjustActivity extends BaseAc<ActivityPicAdjustBinding> {

    public static String imgPath;
    private float myBrightness = 1;//亮度
    private float myContrast = 0;//对比度
    private float mySaturation = 1;//饱和度
    private Bitmap mRetBitmap;
    private Bitmap myBitmap;
    private Dialog myTipDialog;

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_adjust;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivPicAdjustBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.llBrightness.setOnClickListener(this);
        mDataBinding.llContrast.setOnClickListener(this);
        mDataBinding.llSaturation.setOnClickListener(this);
        mDataBinding.ivAdjustSave.setOnClickListener(this);
        //初始化滑动控件
        initSb();
        //调节图片
        adjustImg();
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.llBrightness://亮度
                clearView();
                mDataBinding.sbBrightness.setVisibility(View.VISIBLE);
                mDataBinding.llBrightness.setBackgroundResource(R.drawable.xuanzhong2);
                mDataBinding.ivBrightness.setImageResource(R.drawable.liangdu2);
                mDataBinding.tvBrightness.setTextColor(Color.parseColor("#17191A"));
                break;
            case R.id.llSaturation://饱和度
                clearView();
                mDataBinding.sbSaturation.setVisibility(View.VISIBLE);
                mDataBinding.llSaturation.setBackgroundResource(R.drawable.xuanzhong2);
                mDataBinding.ivSaturation.setImageResource(R.drawable.baohedu2);
                mDataBinding.tvSaturation.setTextColor(Color.parseColor("#17191A"));
                break;
            case R.id.llContrast://对比度
                clearView();
                mDataBinding.sbContrast.setVisibility(View.VISIBLE);
                mDataBinding.llContrast.setBackgroundResource(R.drawable.xuanzhong2);
                mDataBinding.ivContrast.setImageResource(R.drawable.duibidu2);
                mDataBinding.tvContrast.setTextColor(Color.parseColor("#17191A"));
                break;
            case R.id.ivAdjustSave://保存
                if (mRetBitmap != null) {
                    saveImg(mRetBitmap);
                } else {
                    saveImg(myBitmap);
                }
                break;
            //提示弹框
            case R.id.ivDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.ivDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void initData() {
        //获取图片
        if (imgPath == null || TextUtils.isEmpty(imgPath)) return;
        myBitmap = ImageUtils.getBitmap(imgPath);
        Glide.with(this).load(imgPath).into(mDataBinding.imageViewTouch);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        mDataBinding.imageViewTouch.setScaleEnabled(false);// 禁用缩放
    }

    //保存图片
    private void saveImg(Bitmap bitmap) {
        showDialog(getString(R.string.save_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    //初始化控件
    private void initSb() {
        mRetBitmap = null;
        myBrightness = 1;
        mySaturation = 1;
        myContrast = 0;
        mDataBinding.sbBrightness.setProgress(calSeekBarProgress(mDataBinding.sbBrightness,
                myBrightness, ColorTuneRange.BRIGHTNESS));
        mDataBinding.sbSaturation.setProgress(calSeekBarProgress(mDataBinding.sbSaturation,
                mySaturation, ColorTuneRange.SATURATION));
        mDataBinding.sbContrast.setProgress(calSeekBarProgress(mDataBinding.sbContrast,
                myContrast, ColorTuneRange.CONTRAST));
    }

    private float calSeekBarRealValue(SeekBar seekBar, int progress, ColorTuneRange range) {
        int progressRange = seekBar.getMax();
        float value = progress * 1.0f / progressRange * range.getRange() + range.getMin();
        return value;
    }

    private int calSeekBarProgress(SeekBar seekBar, float value, ColorTuneRange range) {
        float valuePercent = (value - range.getMin()) / range.getRange();
        int progress = (int) (seekBar.getMax() * valuePercent);
        return progress;
    }

    //调节图片
    private void adjustImg() {
        //brightness
        mDataBinding.sbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                myBrightness = calSeekBarRealValue(mDataBinding.sbBrightness, progress, ColorTuneRange.BRIGHTNESS);
                //0-2
                float number = myBrightness * 100;
                updateImageViewBitmap();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //saturation
        mDataBinding.sbSaturation.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mySaturation = calSeekBarRealValue(mDataBinding.sbSaturation, progress, ColorTuneRange.SATURATION);
                //0-2
                float number = mySaturation * 100;
                updateImageViewBitmap();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //contrast
        mDataBinding.sbContrast.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                myContrast = calSeekBarRealValue(mDataBinding.sbContrast, progress, ColorTuneRange.CONTRAST);
                //0-360
                float number = myContrast * 10 / 36;
                updateImageViewBitmap();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    //改变图片显示
    private void updateImageViewBitmap() {
        Bitmap preRetBitmap = mRetBitmap;
        mRetBitmap = BmpUtil.adjust(myBitmap, myBrightness, mySaturation, myContrast);
        if (mRetBitmap != null) {
            mDataBinding.imageViewTouch.setImageBitmap(mRetBitmap);
            if (preRetBitmap != null && !preRetBitmap.isRecycled() && preRetBitmap != myBitmap) {
                preRetBitmap.recycle();
            }
        }
    }

    //管理控件
    private void clearView() {
        mDataBinding.sbBrightness.setVisibility(View.GONE);
        mDataBinding.sbSaturation.setVisibility(View.GONE);
        mDataBinding.sbContrast.setVisibility(View.GONE);
        mDataBinding.llBrightness.setBackgroundResource(0);
        mDataBinding.llContrast.setBackgroundResource(0);
        mDataBinding.llSaturation.setBackgroundResource(0);
        mDataBinding.tvBrightness.setTextColor(Color.parseColor("#FFFFFF"));
        mDataBinding.ivBrightness.setImageResource(R.drawable.liangdu1);
        mDataBinding.tvSaturation.setTextColor(Color.parseColor("#FFFFFF"));
        mDataBinding.ivSaturation.setImageResource(R.drawable.baohedu1);
        mDataBinding.tvContrast.setTextColor(Color.parseColor("#FFFFFF"));
        mDataBinding.ivContrast.setImageResource(R.drawable.duibidu1);
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogTipCancel);
        ImageView right = inflate.findViewById(R.id.ivDialogTipRight);
        TextView textView=inflate.findViewById(R.id.tvDialogTipText);
        textView.setText(getString(R.string.image_not_save));
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }


}